package tsb.com.html5.controller.common;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import tsb.com.html5.controller.base.BaseController;
import tsb.com.html5.product.item.CategoryItem;

@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController{
	
	@Autowired
	private MessageSource messageSource;
	
	@RequestMapping(value="/load", method = RequestMethod.GET)
	protected @ResponseBody Map<String, ? extends Object> loadCategory(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HashMap<String, Object> returnMap = new HashMap<String, Object>(); 
		try {
			
			Locale locale = RequestContextUtils.getLocale(request); 
			
			List<CategoryItem> categoryList = this.cacheController.getCategory();
//			setNameInLocale(categoryList, locale);
			
			returnMap.put("category", categoryList);

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return returnMap;
	}
	
	private void setNameInLocale(List<CategoryItem> categoryList, Locale locale){
		if(categoryList!=null && categoryList.size()>0){
			for (CategoryItem categoryItem : categoryList) {
				categoryItem.setNameInLocale(messageSource.getMessage(categoryItem.getName(), null, locale));
				if(categoryItem.getSubCategory()!=null && categoryItem.getSubCategory().size()>0){
					setNameInLocale(categoryItem.getSubCategory(), locale);
				}
			}
		}
		return;
	}
	
}
